from datetime import datetime
import logging
from surrealdb import Surreal
from mitmproxy import http, websocket


class DB:
    def __init__(self):
        # 使用异步方法来初始化异步变量
        self.srrldb = Surreal("ws://localhost:8000/rpc")

    async def connect(self):
        await self.srrldb.connect()
        await self.srrldb.signin({"user": "root", "pass": "root"})
        await self.srrldb.use("test", "test")

        
    # async def save_flow_request(self,flow: http.HTTPFlow):
    #     pretty_url = flow.request.pretty_url
                    
    #     record_id = format(f"http_flow:{flow.id}")  
    #     logging.info(f"\n*****NNNN*** save_flow_request() record_id={record_id}") 
          
    #     await self.srrldb.create(
    #             record_id,
    #             {
    #                 "request_timestamp": str(datetime.utcnow()),
    #                 "request_pretty_url": pretty_url,
    #                 "status":"REQUESTED"
    #             },
    #         )
        


    # async def save_flow_response(self,flow:http.HTTPFlow):
    #     logging.debug("save_flow_response")
    #     if flow.response and len(flow.response.content) > 0:        
    #         # 获取响应头的内容类型值
    #         content_type = flow.response.headers.get("content-type")                

    #         # Parse the charset from the Content-Type header
    #         charset = "utf-8"  # Default to UTF-8 if not specified
    #         if "charset=" in content_type:
    #             charset = content_type.split("charset=")[-1].strip()
            
    #         # Check if the content is likely to be text-based
    #         if "text/" in content_type or "application/json" in content_type:
    #             try:
    #                 # Decode the content using the specified charset
    #                 text_content = flow.response.content.decode(charset)
    #                 # Now you can work with the text_content as a string
    #                 record_id = format("http_flow:{flow.id}")            
    #                 await self.srrldb.update(
    #                     record_id,
    #                     {
    #                         "response_timestamp": str(datetime.datetime.utcnow()),
    #                         "response_charset": charset,
    #                         "response_content_type": content_type,
    #                         "response_content": text_content,
    #                         "status":"RESPONSED"
    #                     },
    #                 )
    #             except UnicodeDecodeError:
    #                 logging.debug(
    #                     f"Failed to decode content using charset: {charset} for pretty_url={pretty_url}")
    #         else:
    #             logging.debug(f"Non-text content, skipping decoding for pretty_url={pretty_url}.")    


